package cn.otrue.patienthealthmanager.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.HealthPlanActivity;
import cn.otrue.patienthealthmanager.activity.LoginActivity;
import cn.otrue.patienthealthmanager.adapter.MainPlanAdapter;
import cn.otrue.patienthealthmanager.bean.PatientPlanModel;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;

import com.google.gson.reflect.TypeToken;

/**
 * 首页->健康计划
 *
 * @author G
 */
public class MainHealthyPlanFragment extends BaseFragment implements
        OnTouchListener {
    private ListView lv_main_plan;
    private List<PatientPlanModel> planData = new ArrayList<PatientPlanModel>();
    private MainPlanAdapter adapter;
    private LinearLayout ll_main_plan_alert;
    private TextView tv_main_plan_add;
    private AlertDialog alertDialog;

    private Handler getPlanListHandler = new ServerHandler() {

        @Override
        public void onSuccess(Bundle data, String state, String msg) {

            if (state.equals(HttpCons.STATE_SUCCESS)) {

                String dataString = data.getString(HttpCons.DATA);
                List<PatientPlanModel> list = HttpServer.gson.fromJson(
                        dataString, new TypeToken<List<PatientPlanModel>>() {
                        }.getType());
                if (list.size() > 0) {
                    planData.clear();
                    planData.addAll(list);
                    // DialogUtil.endProgressDialog(mProgressDialog);
                    ll_main_plan_alert.setVisibility(View.GONE);
                } else {
                    ll_main_plan_alert.setVisibility(View.VISIBLE);
                }
                adapter.notifyDataSetChanged();
            } else {
                Toast.makeText(MainHealthyPlanFragment.this.getActivity(), msg,
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFail(Bundle data, String state) {
            Toast.makeText(MainHealthyPlanFragment.this.getActivity(),
                    "健康计划" + state, Toast.LENGTH_SHORT).show();
        }
    };
    private Calendar calendar;
    private TextView tv_title_other;
    private AlertDialog mProgressDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main_plan,
                container, false);
        calendar = Calendar.getInstance();
        initView(rootView);
        // mProgressDialog = DialogUtil.startProgressDialog(this.getActivity(),
        // "正在加载......");

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
            getData();
        }
    }

    private void initView(View rootView) {
        ll_main_plan_alert = (LinearLayout) rootView
                .findViewById(R.id.ll_main_plan_alert);
        ll_main_plan_alert.setVisibility(View.VISIBLE);
        tv_main_plan_add = (TextView) rootView
                .findViewById(R.id.tv_main_plan_add);
        tv_main_plan_add.setOnClickListener(this);

        lv_main_plan = (ListView) rootView.findViewById(R.id.lv_main_plan);
        adapter = new MainPlanAdapter(rootView.getContext(), planData);
        lv_main_plan.setAdapter(adapter);
        this.isInitViewCompleted = true;
        tv_title_other = ((TextView) getActivity().findViewById(
                R.id.tv_title_other));

    }

    private void getData() {
        /*new Thread(){
            @Override
            public void run() {*/
                TransferParameter parameter = new TransferParameter();
                parameter.setPagesize("5");
                parameter.setCurrentPage("1");

                parameter.setUsername(MyConst.getACCOUNT());
                HashMap<String, Object> data = new HashMap<String, Object>();
                data.put("patientId", MyConst.getACCOUNT());

                CommonUtil.getMaxMonthDate(new Date());
                data.put("begintime", CommonUtil.getMinMonthDate(new Date()));
                data.put("endtime", CommonUtil.getMaxMonthDate(new Date()));
                parameter.setData(data);
                new HttpServer().post(HttpCons.QUERY_PATIENT_RUNPLAN, parameter,
                        getPlanListHandler);
        //    }
       // }.start();
    }

    @Override
    public void onClick(View arg0) {
        if (MyConst.getACCOUNT().equals("")) {

            View dialogView = initDataInputDialog(new DataDialogListener(), 0);
            if (null != dialogView)
                alertDialog = DialogUtil.showDialog(this.getActivity(),
                        dialogView, true);
        } else {
            switch (arg0.getId()) {
                case R.id.tv_main_plan_add:
                case R.id.tv_title_other:
                    Intent intent = new Intent();
                    intent.setClass(this.getActivity(), HealthPlanActivity.class);
                    intent.putExtra("type", MyConst.BLANK_PLAN);
                    intent.putExtra("doctorId", MyConst.getACCOUNT());
                    //startActivity(intent);
                    startActivityForResult(intent, Activity.RESULT_FIRST_USER);
                    break;

                default:
                    break;
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
            getData();
        }
    }

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub
        return false;
    }

    public static Fragment newInstance() {
        return new MainHealthyPlanFragment();
    }

    @Override
    public String setPageName() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private View initDataInputDialog(DataDialogListener dataListener, int i) {
        LayoutInflater inflater = LayoutInflater.from(this.getActivity());
        View view = inflater.inflate(R.layout.dialog_input_daaa, null);
        TextView tv_catt_dialogLeft = (TextView) view
                .findViewById(R.id.tv_catt_dialogLeft);
        tv_catt_dialogLeft.setOnClickListener(dataListener);
        TextView tv_catt_dialogRight = (TextView) view
                .findViewById(R.id.tv_catt_dialogRight);
        tv_catt_dialogRight.setOnClickListener(dataListener);
        return view;

    }

    public class DataDialogListener implements OnClickListener {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.tv_catt_dialogLeft:// 取消

                    break;
                case R.id.tv_catt_dialogRight:// 确定

                    Intent personinfoIntent = new Intent(
                            MainHealthyPlanFragment.this.getActivity(),
                            LoginActivity.class);
                    MainHealthyPlanFragment.this.getActivity().startActivity(
                            personinfoIntent);

            }
            if(alertDialog!=null){
                alertDialog.dismiss();
            }
        }

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
                //getData();
                if (tv_title_other != null) {
                    tv_title_other.setText("我的计划");
                    tv_title_other.setVisibility(View.VISIBLE);
                    tv_title_other.setOnClickListener(this);
                }

            }
            //ll_main_plan_alert.setVisibility(View.VISIBLE);
        }
    }
}
